const http = require('http')
const querystring = require('querystring')


const server = http.createServer((req,res)  =>  {
    const method = req.method
    const url = req.url
    const path = url.split('?')[0]
    const query = querystring.parse(url.split('?')[1])

    //设置返回格式为 JSON
    res.setHeader('Content-type','application/json') //text/html
    
    //返回的数据
    const resDate = {
        method,
        url,
        path,
        query
    } 

    //返回
    if (method == "GET"){
        res.end(
            JSON.stringify(resDate)
        )
    }
    if (method == "POST"){
        let postData = ''
        req.on('data', chunk => {
            postData += chunk.toString()
        })
        req.on('end', () => {
            resDate.postData = postData
            //返回
            res.end(
                JSON.stringify(resDate)
            )
        })
    }


})
server.listen(8000)
console.log('OK 8000')